const http = require('http');
const querystring = require('querystring');
const config = require('./config');
const log = require('./log');
const errCode = require('./code');
var isApplfHight=true;  //是否申请高佣
var getP = false; //是否获取了普通和鹊桥佣金比列
var getCommins = {

    getCallbackFunc:null,
    //设置回调
    setCallbackFunc: function (func) {
        this.getCallbackFunc =func;
    },
    //回调设置的函数
    callBackFunc: function (errCode, data) {
        if (!errCode)  return false;
        var func = this.getCallbackFunc;
        if (typeof func === 'function') {
            data = data || {};
            func(errCode, data);
        }
    },
    //函数类型处理
    callFunc:function(func,data,status,option){
        if(typeof  func ==='function'){
            func(status,data,option);
        }
    },
    //请求事件
    requestHandle:function(response,func,arg){
        var responseText = [];
        var size = 0;
        var call = this;
        response.on('data', function (data) {
            responseText.push(data);
            size += data.length;
        });
        response.on('end', function () {
            responseText = Buffer.concat(responseText, size);
            console.log(responseText.toString());
            try {
                if (!responseText.toString()) {
                    getCommins.callBackFunc(errCode.login);
                    return false;
                }
                var commins = JSON.parse(responseText.toString());
                if (commins.ok) {
                    call.callFunc(func,commins.data,'yes',arg);
                    return true;
                }
                throw  "error";
            } catch (err) {
                call.callFunc(func,null,'no',arg);
                log.createLog(err.message, 'Err.log');
                return false;
            }
        });
        response.on('error', function (e) {
        });
    },

    //请求回调
    requestCall:function(cookies,rq,item,type,func,arg){
        if(!cookies) return false;
        rq = rq || {};
        item = item || {};
        type =type || 'GET';
        var conf = this.getHttpConfig(cookies, rq, item, type);
        if (!conf) {
            return false;
        }
        if(type.toUpperCase() !== 'POST' ){
            conf.re.path = conf.re.path + '?' + conf.arg;
        }
        var call=this;
        var req = http.request(conf.re, function (response) {
            call.requestHandle(response,func,arg);
        });
        if(type.toUpperCase() == 'POST' ){
            req.write(conf.arg);
        }
        req.end();
    },
    //申请高佣
    applfCommins: function (cookies, campId, keeperid) {
        if (!campId || !keeperid) {
            log.createLog('申请高佣失败，没有campId或keeperid' + campId + '#' + keeperid, 'applfComminsErr.log');
            return false;
        }
        var item = {
            campId: campId,
            keeperid: keeperid,
            applyreason: config.sq_remark
        };
        var host = {
            path: config.sq_path
        };
        var conf = this.getHttpConfig(cookies, host, item, 'POST');
        if (!conf) {
            return false;
        }
        var post_req = http.request(conf.re, function (response) {
            var responseText = [];
            var size = 0;
            response.on('data', function (data) {
                responseText.push(data);
                size += data.length;
            });
            response.on('error', function (e) {
                // help.showErr(e.message);
            });
            response.on('end', function () {
                responseText = Buffer.concat(responseText, size);

                try {

                    if (!responseText.toString()) {
                        getCommins.callBackFunc(errCode.login);
                        return false;
                    }
                    var commins = JSON.parse(responseText.toString());
                    if (commins.ok) {
                        getCommins.callBackFunc(errCode.applfLoding,{'status':'yes'});
                        //成功后前端显示信息
                        return true;
                    }
                    throw "error";
                } catch (err) {
                    getCommins.callBackFunc(errCode.applfLoding,{'status':'no'});
                    log.createLog(err.message, 'getComminsError.log');
                    return false;
                }
            });
        });
        post_req.write(conf.arg);
        post_req.end();
    },

    //起始地方：
    start:function(cookies, itemId, url, ad,hight){
        if (!cookies) {
            return false;
        }
        hight =hight || true;
        if(hight && itemId){
            this.searchHightCommins(cookies,itemId);
        }
        if(ad && url){
            this.convertHttp(cookies, url, ad); // 转换链接
        }
    },
    //获取定向佣金比列
    searchHightCommins: function (cookies, itemId, url, ad,hight) {
        if (!cookies || !itemId) {
            return false;
        }
        hight =hight || true;
        var item = {
            itemId: itemId
        };
        this.requestCall(cookies,{path:config.hc_path},item,'GET',getHight,arg);
        return;
        var conf = this.getHttpConfig(cookies, {}, item, 'GET');
        if (!conf) {
            return false;
        }
        conf.re.path = config.hc_path + '?' + conf.arg;
        var get_req = http.request(conf.re, function (response) {
            var responseText = [];
            var size = 0;
            response.on('data', function (data) {
                responseText.push(data);
                size += data.length;

            });
            response.on('end', function () {
                responseText = Buffer.concat(responseText, size);
                console.log(responseText.toString());
                try {
                    if (!responseText.toString()) {
                        getCommins.callBackFunc(errCode.login);
                        return false;
                    }
                    var commins = JSON.parse(responseText.toString());
                    if (commins.ok && commins.data.length > 0) {
                        var data = commins.data;
                        var len = data.length;
                        var exits = false;
                        var campId = keeperid = '';
                        //比较最高佣金
                        for (var i = 0; i < len; i++) {
                            var bstop = true;
                            //高佣若已经申请过则不继续申请
                            if (data[i].Exist) {
                                exits = true;
                                break;
                            }
                            for (var j = 0; j < len; j++) {
                                if (data[i].commissionRate < data[j].commissionRate) {
                                    bstop = false;
                                    break;
                                }
                            }
                            if (bstop) {
                                campId = data[i].CampaignID;
                                keeperid = data[i].ShopKeeperID;
                                break;
                            }
                        }
                        if (hight && !exits && campId && keeperid) {
                            getCommins.applfCommins(cookies, campId, keeperid); //申请高佣
                        }
                        if (ad && url) {
                            getCommins.convertHttp(cookies, url, ad); // 转换链接
                        }
                    }
                } catch (err) {
                    console.log(err);
                    log.createLog(err.message, 'getComminsError.log');
                    return false;
                }
            });
            response.on('error', function (e) {
                console.log(e.message);
            });
        });
        get_req.end();
        return true;
    },
    //获取普通佣金比列:
    searchRate:function (cookie,url) {
        if(!cookie || !url){
            return false;
        }
        var item = { q: url};
        var op = {path:config.search_path};

        this.requestCall(cookie,op,item,'GET',getPuTong);
    },
    //转换链接
    convertHttp: function (cookies, url, adzone) {
        if (!url || !adzone || !cookies) {
            return false;
        }
        var site = adzone.split('_');
        var item = {
            siteid: site[2],
            adzoneid: site[3],
            promotionURL: url,
            _input_charset: 'utf-8'
        };
        var conf = this.getHttpConfig(cookies, {}, item, 'GET');
        if (!conf) {
            return false;
        }
        conf.re.path = config.ad_path + '?' + conf.arg;
        var get_req = http.request(conf.re, function (response) {
            var responseText = [];
            var size = 0;
            response.on('data', function (data) {
                responseText.push(data);
                size += data.length;
            });
            response.on('end', function () {
                responseText = Buffer.concat(responseText, size);
                try {
                    if (!responseText.toString()) {
                        getCommins.callBackFunc(errCode.login);
                        return false;
                    }
                    var commins = JSON.parse(responseText.toString());
                    if (commins.ok) {
                        getCommins.callBackFunc(errCode.convert,{'status':'yes'});
                        log.convertLog(commins.data.sclick);
                        return true;
                    }
                    throw  "error";
                } catch (err) {
                    getCommins.callBackFunc(errCode.convert,{'status':'yes'});
                    log.createLog(err.message, 'convertHttpErr.log');
                    return false;
                }
            });
            response.on('error', function (e) {
            });
        });
        get_req.end();
    },
    //请求的参数信息
    getHttpConfig: function (cookies, r_option, arg_option, type) {
        if (!r_option || !cookies) {
            return false;
        }
        type = type || 'POST';
        arg_option = arg_option || {};
        var date = new Date();
        var reqData = querystring.stringify(Object.assign(arg_option, {
            t: date.getTime(),
            _tb_token_: cookies._tb_token_
        }));
        var param = [];
        for (var i in cookies) {
            param.push(i + '=' + cookies[i]);
        }
        var header = {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Cookie': param.join('; ')
        };
        if (type.toUpperCase() === 'POST') {
            header['Content-Length'] = Buffer.byteLength(reqData);
        }
        var post_options = Object.assign(r_option, {
            host: config.sq_host,
            port: config.sq_port,
            method: type,
            headers: header
        });
        return {
            arg: reqData,
            re: post_options
        };
    }
};


//获取高佣
function getHight(status,data) {
    var len = data.length;
    var exits = false;
    var campId = keeperid = '';
    //比较最高佣金
    for (var i = 0; i < len; i++) {
        var bstop = true;
        //高佣若已经申请过则不继续申请
        if (data[i].Exist) {
            exits = true;
            break;
        }
        for (var j = 0; j < len; j++) {
            if (data[i].commissionRate < data[j].commissionRate) {
                bstop = false;
                break;
            }
        }
        if (bstop) {
            campId = data[i].CampaignID;
            keeperid = data[i].ShopKeeperID;
            break;
        }
    }
    if (!exits && campId && keeperid) {
        getCommins.applfCommins(cookies, campId, keeperid); //申请高佣
    }
    if (ad && url) {

    }
}

//普通佣金
function getPuTong(data,status) {
    getP = true;
    if(status !=='yes'){
        return false;
    }
    var info = data.pageList;
    var avg = info.eventRate;
    var ding = info.tkSpecialCampaignIdRateMap;
    var s=0;
    for(var i in ding){
        if(ding[i] > s){
            s =ding[i];
        }
    }
    if(avg >= s){
        isApplfHight =false;
    }
}




module.exports = getCommins;